import React, { PureComponent } from "react";
import PropTypes from "prop-types";
import { Breadcrumb } from "antd";
import classNames from "classnames";
import menu from "../../common/menu";
import "./index.scss";

function getBreadcrumb(menu, url) {
  const breadcrumbNameMap = menuToBreadcrumbNameMap(menu);

  if (breadcrumbNameMap[url]) {
    return breadcrumbNameMap[url];
  }
  const urlWithoutSplash = url.replace(/\/$/, "");
  if (breadcrumbNameMap[urlWithoutSplash]) {
    return breadcrumbNameMap[urlWithoutSplash];
  }
  let breadcrumb = "";
  Object.keys(breadcrumbNameMap).forEach(item => {
    const itemRegExpStr = `^${item.replace(/:[\w-]+/g, "[\\w-]+")}$`;
    const itemRegExp = new RegExp(itemRegExpStr);
    if (itemRegExp.test(url)) {
      breadcrumb = breadcrumbNameMap[item];
    }
  });
  return breadcrumb;
}

function menuToBreadcrumbNameMap(menu) {
  let breadcrumbNameMap = {};

  menu.map((m, i) => {
    breadcrumbNameMap[m.path] = { name: m.title, path: "" };
    if (m.sub) {
      m.sub.map((ms, j) => {
        breadcrumbNameMap[ms.path] = { name: ms.title, path: ms.path };
      });
    }
  });
}

export default class PageHeader extends PureComponent {
  static contextTypes = {
    match: PropTypes.object
  };
  render() {
    const { match } = this.props;
    let breadcrumb;
    if (match && match.path) {
      const pathSnippets = location.pathname.split("/").filter(i => i);
      const extraBreadcrumbItems = pathSnippets.map((_, index) => {
        const url = `/${pathSnippets.slice(0, index + 1).join("/")}`;
        const currentBreadcrumb = getBreadcrumb(menu, url);
        return (
          <Breadcrumb.Item key={url}>
            <a>{currentBreadcrumb.name || url}</a>
          </Breadcrumb.Item>
        );
      });
      const breadcrumbItems = [
        <Breadcrumb.Item key="home">
          <a>首页</a>
        </Breadcrumb.Item>
      ].concat(extraBreadcrumbItems);
      breadcrumb = (
        <Breadcrumb className="breadcrumb">{breadcrumbItems}</Breadcrumb>
      );
    } else {
      breadcrumb = null;
    }
    return <div className="pageHeader">{breadcrumb}</div>;
  }
}
